package com.hxqc.basic.interceptor;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hxqc.basic.common.Constants;
import com.hxqc.basic.serivce.SysUserService;

public class UserInterceptor implements HandlerInterceptor {

	@Resource
	private SysUserService sysUserService;
	private Set<String> rights;

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception err)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		String path = request.getContextPath();
		if (rights == null) {
			rights = new HashSet<>();
			List<Map<String, Object>> list = sysUserService.findAllRights();
			for (Map<String, Object> map : list) {
				if (null != map.get("access_value"))
					rights.add(path + String.valueOf(map.get("access_value")));
			}
		}
		if (null == request.getSession().getAttribute(Constants.USER_SESSION_KEY)) {
			String requestType = request.getHeader("X-Requested-With");
			if (StringUtils.isNotBlank(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) {
				response.setHeader("sessionstatus", "timeout");
				response.sendError(518, "session timeout.");
			} else {
				PrintWriter out = response.getWriter();
				out.write("<html><script>" + "if(window.parent){window.parent.location.href = '" + path
						+ "/login2.html';}" + "else{location.href='" + path + "/login2.html';}</script></html>");
				out.close();
			}
			return false;
		} else {
			String uri = request.getRequestURI();
			if (rights.contains(uri)) {
				@SuppressWarnings("unchecked")
				Set<String> userRights = (Set<String>) request.getSession().getAttribute(Constants.USER_RIGHT);
				if (!userRights.contains(uri.replaceFirst(path, ""))) {
					request.getSession().removeAttribute(Constants.USER_RIGHT);
					PrintWriter out = response.getWriter();
					out.write("<html><script>" + "if(window.parent){window.parent.location.href = '" + path
							+ "/login.html';}" + "else{location.href='" + path + "/login.html';}</script></html>");
					out.close();
					return false;
				}
			}
		}
		return true;

	}
}